package ui;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.hardware.bcreader.BCRBarCodeValue;
import android.hardware.bcreader.BCRListener;
import android.hardware.bcreader.BCRManager;
import android.hardware.bcreader.BCRTicketInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.IdRes;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sxpjyy.monkey.mobilenurse.R;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import adapters.OrdersExecuteAdapter;
import mytools.ApplicationUtil;
import mytools.DateUtil;
import mytools.MyBaseActivity;
import objects.InPatient;
import objects.JJQXYY;
import objects.OrderDetail;
import service.WebService;

public class OrdersExecuteActivity extends MyBaseActivity implements SwipeRefreshLayout.OnRefreshListener, AdapterView.OnItemLongClickListener, RadioGroup.OnCheckedChangeListener {

    private String TAG = "BCRSample";
    private BCRManager mBCRManager;
    private BCRTicketInfo mBCRTicketInfo[] = {null, null};

    private String mServiceResult = null;
    private String mScanResult;
    private List<OrderDetail> mYZJHList;
    private List<OrderDetail> parentList;
    private List<JJQXYY> mYYList;

    private ProgressDialog progressDialog;
    private MyHandler handler;

    private Toolbar mToolbar;
    private TextView mBRXMText;
    private RadioGroup mRadioGroup;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private ExpandableListView mExpandableListView;
    private OrdersExecuteAdapter mOrdersExecuteAdapter;

    private String ZYH;
    private String ChooseTMBH;
    private String ChooseHDBZ;
    private String mStartDate;
    private String mEndDate;

    private String LXXH = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_orders_execute);
        onBindUI();

        handler = new MyHandler(this);

        BCRListener mListener = new MyListener();
        mBCRManager = BCRManager.getInstance();
        mBCRManager.registerListener(mListener);

        mSwipeRefreshLayout.setColorSchemeResources(R.color.holo_green_dark, R.color.holo_green_light, R.color.holo_orange_light, R.color.holo_red_light);
        mSwipeRefreshLayout.setOnRefreshListener(this);

        mOrdersExecuteAdapter = new OrdersExecuteAdapter(this);
        mExpandableListView.setAdapter(mOrdersExecuteAdapter);
        mExpandableListView.setOnItemLongClickListener(this);

        mRadioGroup.setOnCheckedChangeListener(this);
    }

    private void onBindUI() {
        mToolbar = findViewById(R.id.oe_toolbar);
        mBRXMText = findViewById(R.id.oe_tb_brxm);
        mSwipeRefreshLayout = findViewById(R.id.oe_swipe);
        mExpandableListView = findViewById(R.id.oe_expand);
        mRadioGroup = findViewById(R.id.filter_radiogroup);
    }

    @Override
    protected void onResume() {
        super.onResume();
        InPatient inPatient = getMyApplication().getInPatient();
        if (inPatient != null) {
            ZYH = inPatient.getZYH();
            if (ZYH != null) {
                setToolbar(inPatient.getBRXM());
                Date date = new Date();
//                String dateString = myApplication.getSdf().format(date);

                String dateString=DateUtil.getDFFormatString(date);
                mStartDate = dateString;
                mEndDate = dateString;
                doFlushData(true);
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case 1300:
            case 1301:
                mBCRManager.open(this);
                break;
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void setToolbar(String brxm) {
        mToolbar.setTitle("计划执行");   //设置标题
        mToolbar.setTitleTextColor(Color.WHITE);
        mBRXMText.setText(brxm);
        mBRXMText.setTextColor(Color.WHITE);
        setSupportActionBar(mToolbar);   //必须使用
    }

    @Override
    public void onRefresh() {
        doFlushData(false);
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

        OrderDetail orderDetail = (OrderDetail) mOrdersExecuteAdapter.getGroup(position);
        ChooseTMBH = orderDetail.getTMBH();
        ChooseHDBZ = orderDetail.getHDBZ();
        int yzzt = Integer.valueOf(orderDetail.getYZZT());
        showChooseDialog(this, yzzt);
        return true;
    }

    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        doFilter();
    }

    //扫码监听
    private class MyListener implements BCRListener {
        @Override
        public void onScanFinished(int scanType, String elapseTime) {
            Log.d(TAG, "onScanFinished");
            mBCRTicketInfo = mBCRManager.getTicketInfo();
            Message msg = new Message();
            if (mBCRTicketInfo != null) {
                msg.what = 0x11;
            } else {
                msg.what = 0x99;
            }
            handler.sendMessage(msg);
        }

        @Override
        public void onOpened(boolean isReady) {
            Log.d(TAG, "onOpened");
            if (isReady) {
                mBCRManager.enableCode(BCRBarCodeValue.CODE_TYPE_DATA_MATRIX);
                mBCRManager.enableCode(BCRBarCodeValue.CODE_TYPE_INTERLEAVED_2_OF_5);
                mBCRManager.enableCode(BCRBarCodeValue.CODE_TYPE_PDF417);
                mBCRManager.startScan(BCRManager.SCAN_TYPE_SINGLE, BCRManager.SCAN_MODE_CONTINUE);
            }
        }
    }

    private static class MyHandler extends Handler {

        WeakReference<OrdersExecuteActivity> mActivity;

        MyHandler(OrdersExecuteActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            OrdersExecuteActivity activity = mActivity.get();
            activity.cancelProgressBar();
            switch (msg.what) {
                case 0x99:
                    Toast.makeText(activity, "获取扫描结果失败！", Toast.LENGTH_SHORT).show();
                    activity.mBCRManager.stopScan();
                    break;
                case 0x11: //获取扫描结果成功
                    activity.mBCRManager.stopScan();
                    String result = activity.mBCRTicketInfo[0].getTicketValue();
                    if (result != null && !result.equals("") && !result.equals("failed")) {
                        activity.mScanResult = result;
                    }
                    boolean isFound = false;
                    Integer yzzt = null;

                    for (OrderDetail parent : activity.parentList) {
                        if (parent.getTMBH().equals(activity.mScanResult)) {
                            isFound = true;
                            activity.ChooseTMBH = parent.getTMBH();
                            activity.ChooseHDBZ = parent.getHDBZ();
                            yzzt = Integer.valueOf(parent.getYZZT());
                            break;
                        }
                    }
                    if (isFound) {
                        activity.showChooseDialog(activity, yzzt);
                    } else {
                        Toast.makeText(activity, "当前界面不存在该条码！", Toast.LENGTH_SHORT).show();
                    }
                    break;
                default:
                    break;
            }
        }
    }

    private void showChooseDialog(final Context context, final int yzzt) {
        String[] items = new String[0];
        switch (yzzt) {
            case 0:
                items = new String[]{"计划拒绝", "计划取消", "计划执行"};
                break;
            case 1:
                items = new String[]{"取消完成"};
//                Toast.makeText(context, "医嘱计划已执行,无需操作", Toast.LENGTH_SHORT).show();
//                return;
                break;
            case 2:
                items = new String[]{"取消执行", "计划暂停", "执行完成"};
                break;
            case 4:
                items = new String[]{"暂停恢复", "执行完成"};
                break;
            case 5:
                items = new String[]{"取消拒绝"};
                break;
            case 6:
                Toast.makeText(context, "医嘱计划已取消！", Toast.LENGTH_SHORT).show();
                return;
        }
        if (items.length > 0) {
            AlertDialog.Builder mChooseDialogBuilder = new AlertDialog.Builder(context);
            mChooseDialogBuilder.setTitle("计划操作");
            final String[] finalItems = items;
            mChooseDialogBuilder.setItems(items, (dialog, which) -> {
                String text = finalItems[which];
                switch (text) {
                    case "计划拒绝":
                        showProgressBar(context);
//                            showWarnDialog("是否要拒绝该计划？", "5", "1");
                        String[] parms = new String[]{
                                getMyApplication().getSection().getKSDM()};
                        new MyGetYYTask().execute(parms);
                        break;
                    case "取消拒绝":
                        showWarnDialog("是否要取消拒绝该计划？", "0", null);
                        break;
                    case "计划取消":
                        showWarnDialog("是否要取消该计划？", "6", null);
                        break;
                    case "计划执行":
                        String message;
                        String yzzt1 = "2";
                        if (ChooseHDBZ != null && ChooseHDBZ.equals("1")) {
                            message = "是否要执行该计划？";
                        } else {
                            message = "该医嘱尚未核对，是否继续执行？";
                        }
                        if (!ChooseTMBH.substring(0, 2).equals("SY")) {
                            yzzt1 = "1";
                        }
                        showWarnDialog(message, yzzt1, null);
                        break;
                    case "取消执行":
                        showWarnDialog("是否要取消执行？", "0", null);
                        break;
                    case "计划暂停":
                        showWarnDialog("是否要暂停该计划？", "4", null);
                        break;
                    case "暂停恢复":
                        showWarnDialog("是否要恢复该计划？", "2", null);
                        break;
                    case "执行完成":
                        showWarnDialog("是否要完成该计划？", "1", null);
                        break;
                    case "取消完成":
                        String backYzzt = "0";
                        if (ChooseTMBH.substring(0, 2).equals("SY")) {
                            backYzzt = "2";
                        }
                        showWarnDialog("是否要取消完成？", backYzzt, null);
                        break;
                }
            }).show();
        }
    }

    /**
     * 提示对话框
     *
     * @param msg1 提示信息
     */
    private void showWarnDialog(String msg1, final String yzzt, final String yyxh) {
        AlertDialog.Builder builder = new AlertDialog.Builder(OrdersExecuteActivity.this);
        builder.setMessage(msg1);
        builder.setTitle("提示");
        builder.setPositiveButton("确认", (dialog, which) -> {
            String[] parms = new String[]{getMyApplication().getUser().getYGDM(), ChooseTMBH, yzzt, yyxh};
            new MyExecuteYZJHTask().execute(parms);
            dialog.dismiss();
        });
        builder.setNegativeButton("取消", (dialog, which) -> dialog.dismiss());
        builder.create().show();
    }

    /**
     * 拒绝原因选择对话框
     */
    private void showDenyDialog(String[] items) {
        final String[] yyxh = new String[1];
        AlertDialog.Builder mChooseDialogBuilder = new AlertDialog.Builder(OrdersExecuteActivity.this);
        mChooseDialogBuilder.setTitle("拒绝原因");
        mChooseDialogBuilder.setSingleChoiceItems(items, 0, (dialog, which) -> yyxh[0] = mYYList.get(which).getYYXH());
        mChooseDialogBuilder.setPositiveButton("确认", (dialog, which) -> {
            String[] parms = new String[]{getMyApplication().getUser().getYGDM(), ChooseTMBH, "5", yyxh[0]};
            new MyExecuteYZJHTask().execute(parms);
            dialog.dismiss();
        });
        mChooseDialogBuilder.setNegativeButton("取消", (dialog, which) -> dialog.dismiss());
        mChooseDialogBuilder.create().show();
    }

    //显示等待对话框
    private void showProgressBar(Context context) {
        progressDialog = new ProgressDialog(context);
        progressDialog.setMessage("正在获取信息。。。");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    //取消显示等待对话框
    private void cancelProgressBar() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.cancel();
            progressDialog = null;
        }
    }

    private void doFlushData(boolean isShowProgress) {
        if (isShowProgress) {
            showProgressBar(this);
        }
        String[] parms = {ZYH, mStartDate, mEndDate};
        new MyGetYZJHTask().execute(parms);
    }

    /**
     * 获取医嘱计划操作
     */
    private class MyGetYZJHTask extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... parms) {
            WebService getYZJHWebService = new WebService(OrdersExecuteActivity.this);
            getYZJHWebService.setMETHOD_NAME("getYZJHResult");
            String result;
            getYZJHWebService.setPARMS(parms);
            result = getYZJHWebService.getServerData();
            if (result == null || result.equals("null") || result.equals("") || result.equals("[]")) {
                return "获取医嘱计划列表为空！";
            } else {
                if (!result.equals(mServiceResult)) {
                    mServiceResult = result;
                    Gson gson = new Gson();
                    mYZJHList = gson.fromJson(mServiceResult, new TypeToken<List<OrderDetail>>() {
                    }.getType());
                    if (mYZJHList != null && mYZJHList.size() > 0) {
                        Collections.sort(mYZJHList, (arg0, arg1) -> arg1.getYZZX().compareTo(arg0.getYZZX()));
                        return null;
                    } else {
                        return "获取医嘱计划列表失败!";
                    }
                } else {
                    return "医嘱计划数据未发生变化!";
                }
            }
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            cancelProgressBar();
            if (mSwipeRefreshLayout.isRefreshing()) {
                mSwipeRefreshLayout.setRefreshing(false);
            }
            if (s != null) {
                Toast.makeText(OrdersExecuteActivity.this, s, Toast.LENGTH_SHORT).show();
            } else {
                doFilter();
            }
        }
    }

    private void doFilter() {
        int checkedId = mRadioGroup.getCheckedRadioButtonId();
        switch (checkedId) {
            case R.id.filter_all:
                LXXH = "";
                break;
            case R.id.filter_sy:
                LXXH = "1";
                break;
            case R.id.filter_zs:
                LXXH = "2";
                break;
            case R.id.filter_kf:
                LXXH = "3";
                break;
            case R.id.filter_other:
                LXXH = "4";
                break;
        }
        doSetData();
    }

    private void doSetData() {
        parentList = new ArrayList<>();
        Map<OrderDetail, List<OrderDetail>> mDataSet = new HashMap<>();
        for (OrderDetail ocYZJH : mYZJHList
                ) {
            boolean condition = true;
            if (!LXXH.equals("")) {
                condition = ocYZJH.getLXXH().equals(LXXH);
            }
            if (condition) {
                if (ocYZJH.getYZZX().equals("1")) {
                    parentList.add(ocYZJH);
                    mDataSet.put(ocYZJH, null);
                } else {
                    for (OrderDetail parentYZJH : parentList
                            ) {
                        if (ocYZJH.getTMBH().equals(parentYZJH.getTMBH())) {
                            List<OrderDetail> childList = mDataSet.get(parentYZJH);
                            if (childList == null) {
                                childList = new ArrayList<>();
                            }
                            childList.add(ocYZJH);
                            mDataSet.put(parentYZJH, childList);
                        }
                    }
                }
            }
        }
        mOrdersExecuteAdapter.setDataSets(mDataSet);
        mOrdersExecuteAdapter.notifyDataSetChanged();
    }

    /**
     * 计划操作执行
     */
    private class MyExecuteYZJHTask extends AsyncTask<String, Integer, String> {

        private boolean taskSucceed = false;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            WebService checkWebService = new WebService(OrdersExecuteActivity.this);
            checkWebService.setMETHOD_NAME("executeYZJH");
            String result;
            checkWebService.setPARMS(params);
            result = checkWebService.getServerData();
            if (result == null || result.equals("null") || result.equals("0")) {
                taskSucceed = false;
                return "操作执行失败！";
            } else {
                taskSucceed = true;
                return "操作执行成功！\n" + result;
            }
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            cancelProgressBar();
            if (taskSucceed) {
                doFlushData(true);
            }
            Toast.makeText(OrdersExecuteActivity.this, s, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 获取原因列表
     */
    private class MyGetYYTask extends AsyncTask<String, Integer, String> {


        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            WebService getYZJHWebService = new WebService(OrdersExecuteActivity.this);
            getYZJHWebService.setMETHOD_NAME("getYYWHResult");
            String result;
            getYZJHWebService.setPARMS(params);
            result = getYZJHWebService.getServerData();
            if (result == null || result.equals("null") || result.equals("") || result.equals("[]")) {
                return "获取原因列表为空！";
            } else {
                if (!result.equals(mServiceResult)) {
                    mServiceResult = result;
                    Gson gson = new Gson();
                    mYYList = gson.fromJson(mServiceResult, new TypeToken<List<JJQXYY>>() {
                    }.getType());
                    if (mYYList != null && mYYList.size() > 0) {
//                        Collections.sort(mYYList, new Comparator<JJQXYY>() {
//                            public int compare(JJQXYY arg0, JJQXYY arg1) {
//                                return arg1.getYYXH().compareTo(arg0.getYYXH());
//                            }
//                        });
                        return null;
                    } else {
                        return "获取原因失败!";
                    }
                } else {
                    return "原因数据未发生变化!";
                }
            }
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            cancelProgressBar();
            ArrayList<String> tempList = new ArrayList<>();
            for (JJQXYY yy : mYYList) {
                tempList.add(yy.getYYMC());
            }
            String[] yyitems = tempList.toArray(new String[tempList.size()]);
            Arrays.sort(yyitems);
            if (yyitems.length > 0) {
                showDenyDialog(yyitems);
            }
        }
    }
}
